package com.kkb.mybatis.framework.executor;

import com.kkb.mybatis.framework.config.BoundSql;
import com.kkb.mybatis.framework.config.Configuration;
import com.kkb.mybatis.framework.config.MappedStatement;
import com.kkb.mybatis.framework.handler.StatementHandler;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理普通的JDBC执行
 */
public class SimpleExecutor extends BaseExecutor {

    @Override
    protected List<Object> queryFromDataBase(Configuration configuration, MappedStatement mappedStatement, BoundSql boundSql, Object param) {
        List<Object> results = new ArrayList();
        Connection connection = null;
        ResultSet resultSet = null;
        Statement statement = null;
        try {
            // 连接数据库
            connection = getConnection(configuration);
            String sql = boundSql.getSql();
            StatementHandler statementHandler = configuration.getStatementHandler(mappedStatement.getStatementType());
            statement = statementHandler.prepare(sql, connection);

            // 设置参数
            statementHandler.parameterize(param, statement, boundSql);

            //执行查询
            results = statementHandler.query(statement, mappedStatement);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return results;
    }

    private Connection getConnection(Configuration configuration) {
        try {
            Connection connection = configuration.getDataSource().getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
